class SprintObserver < ActiveRecord::Observer
  observe Sprint

  def before_save(sprint)
    p "SprintObserver: before_save"
    sprint.tasks.each do |task|
      task.estimates.each do |estimate|
        if (estimate.date < sprint.start_date) | (sprint.stop_date < estimate.date)
          estimate.destroy
        end
      end
      
      lastestimate = task.estimates.last

      date = sprint.start_date
	    while date <= sprint.stop_date 
	      estimate = task.estimate_for_date(date)
	      if (estimate == nil)
	        # if we have a new estimate, then if it is before the other estimates
	        # use the initial_estimate.  If it is after the remaining
	        # estimates then use the last estimate available
	        estimate = Estimate.new(:date=>date)
	        # we may not always have estimates yet...
	        if lastestimate.nil?
	          estimate.hours = task.initial_estimate
          else
	          if (estimate.date < lastestimate.date)
  	          estimate.hours = task.initial_estimate
            end
            if (estimate.date > lastestimate.date)
              estimate.hours = lastestimate.hours
            end
          end
        end
	      task.estimates << estimate
	      estimate.save
	      date = date + 1
      end
    end
  end
end
SprintObserver.instance